<?php

require 'pdo.class.php';

class Deia_Model extends DBCONN {

    /**
     * Nome da tabela
     * @var <type>
     */
    public $name = null;
    /**
     * Total de registro retornado pela consulta
     * @var <type>
     */
    public $numTotalRegister = 0;
    /**
     * Contem os limites de cada pagina.f Os valores serão usados para gerar o combo da paginação
     * @var <array>
     */
    public $page = null;           

    /**
     * Cosntrutor da classe
     * @param type $name 
     */
    public function __construct($name = null) {
        $this->name = $name;
        parent::__construct();
    }

    public function save($cod = false) {
        if ($cod) {
            
        } else {

        }
    }

    public function insert($params) {

    }

    public function update($cod) {

    }

    public function delete($cod, $key) {
        if (is_numeric($cod)) {
            try {
                $qwy = $this->prepare("DELETE FROM {$this->name} WHERE {$key} = ?");
                $qwy->execute(array($cod));
            } catch (Exception $e) {
                return $e->getMessage();
            }
        } else {
            return false;
        }
    }

    public function select($params) {
        if (is_array($params)) {
            
        } else {
            return false;
        }
    }

    /**
     *
     * @param <string> $query
     * @param <int> $limit
     * @param <array> $params
     * @return <array>
     */
    public function sql($query, $limit = 0, $params = array()) {
        if (is_array($params) && !empty($query)) {
            if ($limit > 0) {
                $qwyCont = $this->prepare($query);
                $qwyCont->execute($params);

                $rows = $this->query("SELECT FOUND_ROWS()");
                $this->numTotalRegister = $rows->fetchColumn();

                $this->page = $this->pagination($this->numTotalRegister, $limit);

                $pgn = $_POST['pgn'];

                if (!$pgn) {
                    $pgn = "0,{$limit}";
                } else {
                    $pgn = "{$pgn},{$limit}";
                }
                $limit = " LIMIT {$pgn}";
            } else {
                $limit = "";
            }

            $qwy = $this->prepare($query . $limit);
            $qwy->execute($params);

            return $qwy->fetchAll(PDO::FETCH_ASSOC);
        } else {
            return false;
        }
    }

    /**
     *
     * @param <type> $numTotal
     * @param <type> $numPag 
     */
    protected function pagination($numTotal = 0, $numPag = 0) {
        $ini = 0;
        $key = 1;
        for ($ini; $ini < $numTotal; $ini = $ini + $numPag) {
            //$end = $end + $numPag;
            $arrPG[$key] = $ini;
            $key++;
        }

        return $arrPG;

        //var_export($_SESSION);
    }
}